<?php
class Building_Controller extends AdminController {

    public $DISPLAY_LOCALIZED_VALUE_LIST_UUID = 'admin/building/display/localizedValueList';

    public function __construct() {
        parent::__construct('building');
        $this->setDefaultListOrder('code');
    }

    function all() {
        $this->initPagination('building');

        $this->viewData['buildingList'] = $this->dao->queryAll($this->orderLimitAndOffset(
                'SELECT building.*, l10n.* ' .
                'FROM building ' .
                'LEFT OUTER JOIN building_l10n l10n ON building.code = l10n.building_code AND l10n.language_code = :language_code'),
                array('language_code' => $this->getLocalLanguageCode()));
        $this->renderSubview('admin/building/buildingList');
    }

    function display() {
        $code = $this->input->get('code');

        if (! valid::isCode($code)) {
            $this->redirectToList('error.invalidId');
        }

        $building = $this->dao->getLocalizedEntityByCode('building', $code, $this->getLocalLanguageCode());
        if (! $building) {
            $this->redirectToList('error.recordNotFound');
        }
        $this->viewData['building'] = $building;

        $this->viewData['buildingL10nList'] = $this->dao->queryAll(sql::orderBy($this->DISPLAY_LOCALIZED_VALUE_LIST_UUID,
                'SELECT egl.*, l.name as language_name FROM building_l10n egl ' .
                'LEFT OUTER JOIN language l ON l.code = egl.language_code ' .
                'WHERE egl.building_code = :code', 'code'),
                array('code' => $code));

        $this->renderSubview('admin/building/buildingDisplay');
    }

    function edit() {
        $code = $this->input->get('code');

        if ($code) {
            if (! valid::isCode($code)) {
                $this->redirectToList('error.invalidId');
            }

            $building = $this->dao->getByCode('building', $code);
            if (! $building) {
                $this->redirectToList('error.recordNotFound');
            }
        }
        else {
            // default values for a new record
            $building = array(
                'language_code' => $this->getLocalLanguageCode()
            );
        }
        
        $this->loadFormData();

        $this->viewData['building'] = $building;
        $this->renderSubview('admin/building/buildingEdit');
    }

    protected function loadFormData() {
        $this->viewData['languageOptions'] = $this->dao->queryOptions(
                'SELECT l.code, l.name ' .
                'FROM language l ' .
                'ORDER BY l.name');
        $this->viewData['accomodationTypeOptions'] = $this->dao->queryOptions(
                'SELECT accomodation_type_code, name FROM accomodation_type_l10n ' .
                'WHERE language_code = :language_code ORDER BY name',
                array('language_code' => $this->getLocalLanguageCode()));
    }

    public function save() {
        $formData = $this->postToDbValues();
        $code = $formData['code'];
        $this->viewData['building'] = $formData;

        // Basic validation
        $validator = new EntityValidator($formData, 'building', $this->msg);
        $validator->code('code');
        if (! sql::isPersistent($formData)) {
            $validator->code('language_code');
            $validator->required('name');
            $validator->required('description');
        }

        if ($this->msg->hasErrors()) {
            $this->loadFormData();
            $this->publishErrors('admin/building/buildingEdit');
            return;
        }

        // Database validation - unique code
        if (! sql::isPersistent($formData)) {
            $existingEntity = $this->dao->getByCode('building', $code);
            if ($existingEntity) {
                $this->msg->error('building.error-alreadyExists-code', $code);
            }
        }
        if ($this->msg->hasErrors()) {
            $this->loadFormData();
            $this->publishErrors('admin/building/buildingEdit');
            return;
        }

        // Insert or update
        $buildingEntity = new Building_Model($formData);
        if ($buildingEntity->isPersistent()) {
            $this->dao->updateEntity($buildingEntity);
            $this->msg->info('building.editSuccess', $buildingEntity->get('code'));
        }
        else {
            $this->dao->insertEntity($buildingEntity);
            
            // Insert localized values
            $buildingL10n = new BuildingL10n_Model($formData);
            $this->dao->insertEntity($buildingL10n);
            $this->msg->info('building.createSuccess', $buildingL10n->get('name'));
        }
        
        $this->ajaxSuccessOrRedirect('/admin/building/display?code=' . $code, $formData);
    }

    function delete() {
        $code = $this->input->get('code');

        if (! valid::isCode($code)) {
            $this->redirectToList('error.invalidId');
        }

        // Basic validation
        $building = $this->dao->getLocalizedEntityByCode('building', $code, $this->getLocalLanguageCode());
        if (! $building) {
            $this->redirectToList('error.recordNotFound');
        }

        // Delete the record, localization values are deleted by cascading.
        $this->dao->deleteByCode('building', $code);

        $this->msg->info('building.deleteSuccess', $building['name']);
        $this->redirectToList();
    }

    function editLocalizedValues() {
        $code = $this->input->get('building_code');
        $languageCode = $this->input->get('language_code');

        if (! valid::isCode($code)) {
            $this->redirectToList('error.invalidId');
        }

        $building = $this->dao->getLocalizedEntityByCode('building', $code, $this->getLocalLanguageCode());
        if (! $building) {
            $this->redirectToList('error.recordNotFound');
        }
        $this->viewData['building'] = $building;

        if (valid::isCode($languageCode)) {
            $formData = $this->dao->getUnique('building_l10n',
                    array(
                        'building_code' => $code,
                        'language_code' => $languageCode
                    ));
            if (! $formData) {
                $this->redirectToList('error.recordNotFound');
            }
        }
        else {
            // Default values
            $formData = array('building_code' => $code);
        }
        $this->viewData['formData'] = $formData;

        $this->localizedValuesData($code, $languageCode);
        $this->renderMySubview('buildingL10nEdit');
    }

    function localizedValuesData($buildingCode, $languageCode) {
        $params = array('code' => $buildingCode);
        $query = 'SELECT l.code, l.name ' .
                    'FROM language l ' .
                    'WHERE l.code NOT IN (SELECT egl.language_code FROM building_l10n egl WHERE egl.building_code = :code) ';
        if ($languageCode) {
            $query .= 'OR l.code = :language_code ';
            $params['language_code'] = $languageCode;
        }
        $query .= 'ORDER BY l.name';
        $this->viewData['languageOptions'] = $this->dao->queryOptions($query, $params);
    }

    function saveLocalizedValues() {
        $formData = $this->postToDbValues();
        $code = $formData['building_code'];
        $this->viewData['formData'] = $formData;
        $languageCode = $formData['language_code'];
        if (! valid::isCode($code)) {
            $this->redirectToList('error.invalidId');
        }

        $building = $this->dao->getLocalizedEntityByCode('building', $code, $this->getLocalLanguageCode());
        if (! $building) {
            $this->redirectToList('error.recordNotFound');
        }
        $this->viewData['building'] = $building;

        // Basic validation
        $validator = new EntityValidator($formData, 'building', $this->msg);
        $validator->code('language_code');
        $validator->required('name');
        $validator->required('description');
        if ($this->msg->hasErrors()) {
            $this->localizedValuesData($code, $languageCode);
            $this->publishErrors('admin/building/buildingL10nEdit');
            return;
        }

        $language = $this->dao->getByCode('language', $languageCode);
        if (! $language) {
            $this->redirectToList('error.recordNotFound');
        }

        $buildingL10nEntity = new BuildingL10n_Model($formData);
        
        if (! $buildingL10nEntity->isPersistent()) {
            // Check if we don't have already this language
            $existingL10n = $this->dao->getByPrimaryKey($buildingL10nEntity);
            if ($existingL10n) {
                $this->msg->error('errors.translationAlreadyExists', $language['name']);
                $this->localizedValuesData($code, $languageCode);
                $this->publishErrors('admin/building/buildingL10nEdit');
            }

            $this->dao->insertEntity($buildingL10nEntity);
            $this->msg->info('building.createL10nSuccess', $buildingL10nEntity->get('name'), $language['name']);
        }
        else {
            $this->dao->updateEntity($buildingL10nEntity);
            $this->msg->info('building.editL10nSuccess', $buildingL10nEntity->get('name'), $language['name']);
        }

        $this->redirect('/admin/building/display?code=' . $code);
    }

    function deleteLocalizedValues() {
        $code = $this->input->get('building_code');
        $languageCode = $this->input->get('language_code');

        if (! valid::isCode($code) || ! valid::isCode($languageCode)) {
            $this->redirectToList('error.invalidId');
        }

        $building = $this->dao->getLocalizedEntityByCode('building', $code, $this->getLocalLanguageCode());
        if (! $building) {
            $this->redirectToList('error.recordNotFound');
        }

        $language = $this->dao->getByCode('language', $languageCode);
        if (! $language) {
            $this->redirectToList('error.recordNotFound');
        }

        $buildingL10nEntity = new BuildingL10n_Model($_GET);

        $existingRecord = $this->dao->getByPrimaryKey($buildingL10nEntity);
        if (! $existingRecord) {
            $this->redirectToList('error.recordNotFound');
        }

        $this->dao->deleteEntity($buildingL10nEntity);

        $this->msg->info('building.deleteL10nSuccess', $building['name'], $language['name']);
        $this->redirect('/admin/building/display?code=' . $code);
    }
    
    function orderForm() {
        $this->viewData['buildingList'] = $this->dao->queryAll(
                'SELECT building.*, l10n.* ' .
                'FROM building ' .
                'LEFT OUTER JOIN building_l10n l10n ON building.code = l10n.building_code AND l10n.language_code = :language_code ' .
                'ORDER BY building.order_number', 
                array('language_code' => $this->getLocalLanguageCode()));
        $this->renderSubview('admin/building/buildingOrder');
    }
    
    function orderSave() {
        $itemOrder = $this->input->post('itemOrder');
        $index = 1;
        foreach ($itemOrder as $code) {
            $building = $this->dao->getByCode('building', $code);
            $building['order_number'] = $index;
            $this->dao->update('building', $building, 'code');
            $index++;
        }
        $this->msg->info('application.orderSave-success');
        $this->redirect('/admin/building/all');
    }
}
